<script setup lang="ts">
import {computed, onMounted, ref, watch} from "vue";
import {useStore} from "vuex";
import {
  addPrivateChatUser,
  getMessageList,
  getPrivateChatUserList,
  getUserMessageList,
  attention_list,
  attention_handle
} from "@/api/user"
import {Message} from "view-ui-plus";


const store = useStore();
const UserData = store.state.UserData;// 当前用户的ID

watch(() => store.state.socketMessage, (data => {
  let message = data;
  try {
    message = JSON.parse(data);
    console.log(message, 'message')
    if (message.type == "onLine") {
      // 获取在线人数并输出到列表
      console.log('获取在线人数并输出到列表')
      messageList.value.push({
        name: '系统',
        outimg: 'https://resources.wzhyt.cn/images/boy.png',
        content: `当前在线人数：${(JSON.parse(message.content)).length}人\n\n` + message.content
      });
      gotoTop();
    } else if (message.type == "messageUpdateStatus") {
      // 更新发送消息的状态
      messageList.value.forEach(function (item) {
        if (item.timestamp == message.timestamp) {
          item.status = message.status;
        }
      })
    } else if (message.type == "newMessage") {
      // 接收除自己外的群发消息
      messageList.value.push({
        name: message.name,
        user_id: message.user_id,
        outimg: message.outimg,
        content: message.content
      });
      gotoTop();
    } else if (message.type == "newUserMessage") {
      // 接收私聊消息
      if (selectUserObject.value.user_id == message.user_id) {
        // 判断当前窗口是否在私聊窗口下
        messageList.value.push({
          name: message.name,
          user_id: message.user_id,
          outimg: message.outimg,
          content: message.content
        });
        gotoTop();

      }
    } else if (message.type == "updateUserList") {
      // 刷新用户列表
      getPrivateChatUserListContent();
    }
  } catch (e) {
    // 字符串输出
    // console.log(e,'error')
  }
  console.log(message, "========根据data获取的数据")
}))

let search = ref('');// 搜索框
let messageContentText = ref('');// 发送消息输入框文本
let selectUserList = ref([
  {user_id: 'public', name: '公开群组', outimg: 'https://resources.wzhyt.cn/images/ey.png'},
]);
// let selectUserIndex = ref<any>(0);// 选中的聊天索引
let selectUserObject = ref(selectUserList.value[0])

let messageList = ref<any>([]);// 消息列表

let messageListRef = ref();// 消息聊天列表ref

let showRightMenu = ref(false);// 显示右击菜单

let loading = ref(false);

let current = ref(1); // 当前的页数

let location = ref({
  left: 0,
  top: 0
});

let rightClickObject = ref<any>({});// 右击用户头像的信息
// let isAttention = ref(false);// 是否关注用户
let AttentionList = ref([]);// 关注列表

const isAttention = computed(() => {
  let is = AttentionList.value.find(item => item == rightClickObject.value.user_id);
  if (is) {
    return true;
  } else {
    return false;
  }
})


const styles = computed(() => {
  return {
    left: location.value.left + 'px',
    top: location.value.top + 'px'
  }
})

const searchList = computed(() => {
  // 根据输入框的文字过滤出显示的用户列表
  return selectUserList.value.filter(item => {
    return item.name.indexOf(search.value) > -1
  })
})

const selectUser = (item: any) => {
  // 选中聊天对象
  current.value = 1;
  let user_id = selectUserObject.value.user_id;
  if (user_id == item.user_id) {
    return;
  }
  selectUserObject.value = item;
  user_id = selectUserObject.value.user_id;
  messageList.value = [];
  getMessageHistory(user_id == 'public' ? 'public' : 'private')
  // if (user_id !== "public") {
  // }
}

const addPrivateUser = (user_id: string) => {
  // 添加私聊用户进列表
  addPrivateChatUser({
    user_id: user_id
  }).then(result => {
    console.log(result)
    store.commit('socketSend', {
      type: 'updateUserList',
      user_id: user_id
    })
  })
}
const sendText = () => {
  // 发送消息
  const timestamp = Date.now();// 发送的时间戳 留着对比数据发送状态
  const text = messageContentText.value; // 发送的消息
  if (text == "&getLength") {
    store.commit('socketSend', {
      type: 'onLine'
    })
    messageList.value.push({
      name: UserData.name,
      outimg: UserData.outimg,
      content: text,
      status: 'success',
      user_id: UserData.user_id,
      timestamp: timestamp
    });
    messageContentText.value = '';
    gotoTop();
    return;
  }
  messageList.value.push({
    name: UserData.name,
    outimg: UserData.outimg,
    content: text,
    status: 'loading',
    user_id: UserData.user_id,
    timestamp: timestamp
  });
  setTimeout(() => {
    if (selectUserObject.value.user_id == 'public') {
      // 发送群消息
      store.commit('socketSend', {
        type: 'sendMessage',
        content: text,
        timestamp: timestamp
      })
    } else {
      // 发送私聊消息
      store.commit('socketSend', {
        type: 'sendUserMessage',
        accept_user_id: selectUserObject.value.user_id,
        content: text,
        timestamp: timestamp
      })
    }

  }, 1500)
  messageContentText.value = '';
  gotoTop();
}

const close = () => {
  // 断开连接
  store.state.websocket.close();
}

const gotoTop = () => {
  // 回到顶部
  setTimeout(() => {
    messageListRef.value.scrollTop = Date.now();
  })
}

const clickOutimg = function (e: any, item: any) {
  // 右击聊天对象的头像
  e.preventDefault();
  // console.log(e.clientX, e.clientY);
  location.value = {
    left: e.clientX,
    top: e.clientY
  }
  showRightMenu.value = true;
  rightClickObject.value = item;
}

const privateChat = () => {
  // 用户私聊
  let user_id = rightClickObject.value.user_id;
  if (user_id == UserData.user_id) {
    showRightMenu.value = false;
    return Message.error('不可以跟自己聊天哦');
  }
  if (!selectUserList.value.find(item => item.user_id == user_id)) {
    selectUserList.value.push(rightClickObject.value);// 添加进消息列表
    addPrivateUser(user_id);
  }
  showRightMenu.value = false;
  selectUser(rightClickObject.value);
}

const getPrivateChatUserListContent = () => {
  // 获取所有在私聊的用户列表
  getPrivateChatUserList().then(result => {
    console.log(result)
    selectUserList.value = [
      ...selectUserList.value,
      ...result.data
    ]
  })
}
const GoAttention = () => {
  // 关注用户
  attention_handle({
    status: (!isAttention.value) ? 1 : 0,
    a_id: rightClickObject.value.user_id
  }).then((result: any) => {
    console.log(result)
    get_attention_list();
    if (result.code == 200) {
      Message.success(result.data)
    } else {
      Message.error(result.data)
    }
  })
}

const loadmore = () => {
  // 加载更多
  console.log("loadmore")
  loading.value = true;
  current.value = current.value + 1;
  let user_id = selectUserObject.value.user_id;
  getMessageHistory(user_id == 'public' ? 'public' : 'private', true);
}

const getMessageHistory = (type: string = 'public', status: boolean = false) => {
  if (type == 'public') {
    getMessageList({
      pageSize: 10,
      pageNo: current.value
    }).then(result => {
      console.log(result)
      loading.value = false;
      if (status) {
        result.data.data.forEach((item: any) => {
          messageList.value.unshift(item)
        })
      } else {
        messageList.value = result.data.data;
        gotoTop();
      }
      get_attention_list()
    })
  } else if (type == "private") {
    // 私聊
    getUserMessageList({
      accept_user_id: selectUserObject.value.user_id,
      pageSize: 10,
      pageNo: current.value
    }).then(result => {
      console.log(result)
      loading.value = false;
      if (status) {
        result.data.data.forEach((item: any) => {
          messageList.value.unshift(item)
        })
      } else {
        messageList.value = result.data.data;
        gotoTop();
      }
      get_attention_list()
    })
  }
}

const get_attention_list = () => {
  // 获取用户关注列表
  attention_list().then((result: any) => {
    AttentionList.value = result.data;
  })
}

onMounted(() => {
  getPrivateChatUserListContent();
  getMessageHistory()
})
</script>

<template>
  <div class="messageMain">
    <div class="messageContent">
      <div class="messageLeft">
        <div class="search">
          <Input
              prefix="ios-search"
              class="input-with"
              :border="false"
              v-model="search"
              placeholder="搜索"
          >
          </Input>
        </div>
        <div class="userList">
          <div class="userItem" :class="{active:selectUserObject.user_id==item.user_id}" @click="selectUser(item)"
               v-for="(item,index) in searchList" :key="index">
            <div class="avatar">
              <img :src="item.outimg" alt="">
            </div>
            <div class="name">
              <div class="nickname">{{ item.name }}</div>
            </div>
          </div>
        </div>
      </div>
      <div class="messageRight">
        <div class="messageUserTitle">
          {{ selectUserObject.name }}
        </div>
        <div class="messageList" ref="messageListRef" @click.stop="showRightMenu=false">
          <div class="loadmore" v-if="messageList.length >= 10">
            <a v-if="!loading" @click="loadmore">加载更多</a>
            <Icon v-else type="ios-loading" size=18 class="icon-loading"></Icon>
          </div>
          <div class="messageItem" :class="{isMe:item.user_id==UserData.user_id}"
               v-for="(item,index) in messageList" :key="index">
            <div class="avatar" @contextmenu="clickOutimg($event,item)">
              <img :src="item.outimg" alt="">
            </div>
            <div class="name">
              <div class="nickname">{{ item.name }}</div>
              <div class="messageBubble">
                {{ item.content }}
                <Icon v-show="item.status == 'loading'" type="ios-loading" size="15" class="demo-spin-icon-load"></Icon>
              </div>
            </div>
          </div>
        </div>
        <div class="messageSendInfo">
          <!--          @keyup.enter="sendText"-->
          <textarea class="textarea" v-model="messageContentText"></textarea>
          <div class="btnsSend">
            <!--            <div class="btnGet" @click="getOnline">获取在线人数</div>-->
            <!--            <div class="btnGet" @click="close">断开连接</div>-->
            <div class="btnSend" @click="sendText">发送</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <div class="rightMenu" :style="styles" v-if="showRightMenu">
    <div class="hoverInfo">
      <div class="outimg">
        <img :src="rightClickObject.outimg" alt="">
      </div>
      <div class="info">
        <span><b>{{ rightClickObject.name }}</b>（{{ rightClickObject.username }}）</span>
        <div v-line-clamp="3">{{ rightClickObject.intro }}</div>
      </div>
    </div>
    <div class="utils">
      <div class="attention" :class="{active:isAttention}" @click="GoAttention">{{
          isAttention ? "已关注" : "关注"
        }}
      </div>
      <div class="chat" @click="privateChat">聊天</div>
    </div>
  </div>
</template>

<style>
.demo-spin-icon-load {
  position: absolute;
  color: #65ad6a;
  position: absolute;
  bottom: 8px;
  animation: ani-demo-spin 1s linear infinite;
}

.icon-loading {
  animation: ani-demo-spin 1s linear infinite;
}

@keyframes ani-demo-spin {
  from {
    transform: rotate(0deg);
  }
  50% {
    transform: rotate(180deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

<style scoped lang="scss">
.rightMenu {
  position: fixed;
  width: 300px;
  background-color: #fff;
  z-index: 9999;
  padding: 10px;
  box-shadow: 0 0 10px 1px rgba(0, 0, 0, 0.1);
  border-radius: 6px;


  .hoverInfo {
    display: flex;
    width: 100%;

    .outimg {
      font-size: 0;

      img {
        width: 80px;
        height: 80px;
      }
    }

    .info {
      width: calc(100% - 80px);
      padding-left: 10px;
      white-space: pre-line;
      font-size: 14px;
      line-height: 1.4;

      > span {
        font-size: 16px;
      }
    }
  }

  .utils {
    margin-top: 5px;
    line-height: 1;
    text-align: center;
    display: flex;
    justify-content: space-between;

    .attention {
      width: calc(50% - 5px);
      font-size: 14px;
      padding: 5px 0;
      color: #666;
      border: 1px solid #ddd;
      cursor: pointer;
      user-select: none;
    }

    .chat {
      width: calc(50% - 5px);
      font-size: 14px;
      padding: 5px 0;
      color: #666;
      border: 1px solid #ddd;
      cursor: pointer;
      user-select: none;
    }

    .active {
      background-color: #65ad6a;
      border-color: #65ad6a;
      color: #fff;
    }
  }
}

.messageMain {
  width: 100%;
  height: calc(100vh - 85px);
  display: flex;

  .messageContent {
    width: 900px;
    height: 90%;
    background-color: #f2f2f2;
    box-shadow: 1px 5px 10px 1px rgba(129, 129, 129, 0.2);
    margin: auto;
    border-radius: 18px;
    overflow: hidden;
    display: flex;

    .messageLeft {
      width: 200px;
      height: 100%;
      background-color: #fff;
      border-right: 1px solid #ddd;

      .search {
        padding: 0 15px;
        height: 60px;
        background-color: #fff;
        display: flex;
        align-items: center;

        :deep(.input-with) {
          .ivu-input {
            background-color: #f2f2f2;
            border-radius: 4px !important;

          }
        }
      }

      .userList {
        height: calc(100% - 60px);
        overflow-y: scroll;

        .userItem {
          padding: 10px 15px;
          display: flex;

          &:hover {
            background-color: #f2f2f2;
          }

          &.active {
            background-color: #e7e7e7;
          }

          .avatar {
            img {
              width: 40px;
              height: 40px;
              border-radius: 50%;
            }
          }

          .name {
            padding-left: 10px;

            .nickname {

            }
          }
        }
      }
    }

    .messageRight {
      width: 700px;
      height: 100%;

      .messageUserTitle {
        display: flex;
        align-items: center;
        height: 60px;
        padding: 0 15px;
        background-color: #fff;
        font-weight: 500;
        font-size: 16px;
      }

      .messageList {
        height: calc(100% - 180px);
        padding-bottom: 10px;
        overflow-y: scroll;

        .loadmore {
          display: flex;
          padding: 10px 0;
          justify-content: center;
          position: relative;
        }

        .messageItem {
          padding: 15px 15px 5px;
          display: flex;

          &.isMe {
            flex-direction: row-reverse;

            .name {
              padding: 0 10px 0 0;
              display: flex;
              flex-direction: column;
              align-items: flex-end;
            }

            .nickname {
              text-align: right;
            }

            :deep(.demo-spin-icon-load) {
              left: -20px;
            }
          }

          :deep(.demo-spin-icon-load) {
            right: -20px;
            right: auto;
          }

          .avatar {
            img {
              width: 40px;
              height: 40px;
              border-radius: 50%;
            }
          }

          .name {
            font-weight: 400;
            padding: 0 0 0 10px;
            display: flex;
            flex-direction: column;
            flex: 1;

            .nickname {
              width: fit-content;

            }

            .messageBubble {
              width: fit-content;
              white-space: pre-wrap;
              word-break: break-all;
              max-width: calc(100% - 100px);
              position: relative;
              font-size: 14px;
              font-weight: 400;
              color: #fff;
              margin-top: 5px;
              padding: 6px 12px;
              border-radius: 8px;
              background-color: #65ad6a;
            }
          }
        }
      }

      .messageSendInfo {
        height: 120px;
        border-top: 1px solid #ddd;
        display: flex;
        flex-direction: column;

        .btnsSend {
          display: flex;
          padding: 5px;

          .btnGet, .btnSend {
            padding: 5px 18px;
            border-radius: 4px;
            background-color: #65ad6a;
            color: #fff;
            cursor: pointer;
            margin-right: 10px;
            user-select: none;
          }

          .btnSend {

          }
        }

        .textarea {
          width: 100%;
          //height: 100%;
          flex: 1;
          padding: 15px 15px 0;
          border: none;
          outline: none;
          resize: none;
          font-size: 14px;
          font-weight: 400;
          color: #666;
          background-color: #f2f2f2;
        }

      }
    }
  }
}
</style>
